package com.imay.live.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.imay.live.activity.family.util.LevelUtil;
import com.imay.live.adapter.DynamicsIndicatorAdapter;
import com.imay.live.fragment.RankingFragment;
import com.imay.live.manager.FamilyAccountManager;
import com.imay.live.model.RankingModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.R;
import com.imay.live.utils.GlideUtil;
import com.imay.live.utils.ViewUtil;
import com.imay.live.view.indicator.Indicator;
import com.imay.live.view.indicator.ScrollIndicatorView;
import com.imay.live.view.indicator.slidebar.ColorBar;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jeaman on 2017/5/17.
 * 房间7天礼物排行
 */

public class RoomRankingActivity extends BaseRequestActivity {
    private static final String EXTRA_NAME_ROOM_ID = "room_id";
    private static final String EXTRA_IS_OWER = "is_ower";

    private String requestMeiliMonthCommand, requestMeiliDayCommand;

    private RankingFragment mRankingFragment;
    private long mRoomId;
    private List<RankingModel> rankingGainMeiliMonthModels, rankingGainMeiliDayModels;
    private RankingModel myRankingMonthModel, myRankingDayModel;

    public static void startActivity(Context context, long roomId, boolean isOwer) {
        Intent intent = new Intent(context, RoomRankingActivity.class);
        intent.putExtra(EXTRA_NAME_ROOM_ID, roomId);
        intent.putExtra(EXTRA_IS_OWER, isOwer);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_room_ranking;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mRoomId = getIntent().getLongExtra(EXTRA_NAME_ROOM_ID, 0);

        /**
         * 头部
         */
        final ScrollIndicatorView dynamcisHead = (ScrollIndicatorView) LayoutInflater.from(this).inflate(R.layout.view_dynamics_title, null);
        String[] tabTitles = new String[]{getString(R.string.room_ranking_title_day), getString(R.string.room_ranking_title_month)};
        ColorBar colorBar = new ColorBar(this, Color.TRANSPARENT, (int) getResources().getDimension(R.dimen.size_3dp));
        colorBar.setWidth((int) getResources().getDimension(R.dimen.tab_ind_w));
        dynamcisHead.setScrollBar(colorBar);
        DynamicsIndicatorAdapter mIndicatorAdapter = new DynamicsIndicatorAdapter(this, getSupportFragmentManager(), tabTitles, R.layout.view_indicator_tab3);
        dynamcisHead.setAdapter(mIndicatorAdapter.getIndicatorAdapter());
        dynamcisHead.setOnTransitionListener(new Indicator.OnTransitionListener() {
            @Override
            public void onTransition(View view, int position, float selectPercent) {
                if (selectPercent == 0.0) {
                    TextView itemView1 = (TextView) dynamcisHead.getItemView(0);
                    if (itemView1 != null) {
                        itemView1.getPaint().setFakeBoldText(true);
                    }

                    TextView itemView2 = (TextView) dynamcisHead.getItemView(1);
                    if (itemView2 != null) {
                        itemView2.getPaint().setFakeBoldText(true);
                    }

                    TextView itemView = (TextView) dynamcisHead.getItemView(position);
                    if (itemView != null) {
                        itemView.getPaint().setFakeBoldText(false);
                    }
                }
            }
        });
        getTitleBar().getMiddleView().addView(dynamcisHead);

        mRankingFragment = RankingFragment.newInstance(RankingFragment.TYPE_DAYRANKING);

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.room_ranking_fl_root, mRankingFragment);
        ft.commitAllowingStateLoss();

        rankingGainMeiliMonthModels = new ArrayList<>();
        rankingGainMeiliDayModels = new ArrayList<>();

        dynamcisHead.setOnItemSelectListener(new Indicator.OnItemSelectedListener() {
            @Override
            public void onItemSelected(View selectItemView, int select, int preSelect) {
                requestData(select);
            }
        });
        dynamcisHead.setCurrentItem(0);
        requestData(0);
    }

    private void requestData(int select) {
        if (select == 0) {
            if (rankingGainMeiliDayModels.isEmpty()) {
                requestMeiliDayCommand = ProtoRequestHelper.task(ProtoHttpFactory.getRoomRankingList(mRoomId, 1)).request(this);
            } else {
                mRankingFragment.setRankingData(rankingGainMeiliDayModels, getIntent().getBooleanExtra(EXTRA_IS_OWER, false));
                setMyRank(myRankingDayModel);
            }
        } else if (select == 1) {
            if (rankingGainMeiliMonthModels.isEmpty()) {
                requestMeiliMonthCommand = ProtoRequestHelper.task(ProtoHttpFactory.getRoomRankingList(mRoomId, 2)).request(this);
            } else {
                mRankingFragment.setRankingData(rankingGainMeiliMonthModels, getIntent().getBooleanExtra(EXTRA_IS_OWER, false));
                setMyRank(myRankingMonthModel);
            }
        }
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        if (command.equals(requestMeiliMonthCommand)) {
            Result<JSONObject> result = JSON.parseObject(data, new TypeReference<Result<JSONObject>>() {
            }.getType());
            if (result.result == ResultCode.CodeSuccess && result.data != null) {
                if (result.data.containsKey("RankList")) {
                    List<RankingModel> rankingModels = JSON.parseObject(result.data.getString("RankList"), new TypeReference<List<RankingModel>>() {
                    }.getType());
                    rankingGainMeiliMonthModels.addAll(rankingModels);
                    mRankingFragment.setRankingData(rankingModels, getIntent().getBooleanExtra(EXTRA_IS_OWER, false));
                }
                if (result.data.containsKey("MyRankData")) {
                    myRankingMonthModel = JSON.parseObject(result.data.getString("MyRankData"), RankingModel.class);
                    setMyRank(myRankingMonthModel);
                }
            }
        } else if (command.equals(requestMeiliDayCommand)) {
            Result<JSONObject> result = JSON.parseObject(data, new TypeReference<Result<JSONObject>>() {
            }.getType());
            if (result.result == ResultCode.CodeSuccess && result.data != null) {
                if (result.data.containsKey("RankList")) {
                    List<RankingModel> rankingModels = JSON.parseObject(result.data.getString("RankList"), new TypeReference<List<RankingModel>>() {
                    }.getType());
                    rankingGainMeiliDayModels.addAll(rankingModels);
                    mRankingFragment.setRankingData(rankingModels, getIntent().getBooleanExtra(EXTRA_IS_OWER, false));
                }
                if (result.data.containsKey("MyRankData")) {
                    myRankingDayModel = JSON.parseObject(result.data.getString("MyRankData"), RankingModel.class);
                    setMyRank(myRankingDayModel);
                }
            }
        }
    }

    public void setMyRank(RankingModel myRank) {
        if (myRank != null) {
            boolean isOwer = getIntent().getBooleanExtra(EXTRA_IS_OWER, false);
            if (isOwer) {
                ViewUtil.findView(this, R.id.item_ranking_normal_me).setVisibility(View.GONE);
                ViewUtil.findView(this, R.id.item_ranking_img_me).setVisibility(View.GONE);
            } else {
                ViewUtil.findView(this, R.id.item_ranking_normal_me).setVisibility(View.VISIBLE);
                ViewUtil.findView(this, R.id.item_ranking_img_me).setVisibility(View.VISIBLE);
            }
            ImageView iv_hear_img_ranking = ViewUtil.findView(this, R.id.iv_hear_img_ranking);
            GlideUtil.loadCircleImage(iv_hear_img_ranking, myRank.getUser().getImgHead(), R.mipmap.pnl_00_head108);

            ViewUtil.findView(this, R.id.tv_anchor_level_ranking).setVisibility(View.GONE);
            ViewUtil.findView(this, R.id.tv_user_level_ranking).setVisibility(View.GONE);
            ViewUtil.findView(this, R.id.ll_follow).setVisibility(View.INVISIBLE);

            TextView tv_name_ranking = ViewUtil.findView(this, R.id.tv_name_ranking);
            tv_name_ranking.setText(myRank.getUser().getNick());

            TextView tv_anchor_family_ranking = ViewUtil.findView(this, R.id.tv_anchor_family_ranking);
            tv_anchor_family_ranking.setTextColor(this.getResources().getColor(LevelUtil.getLevelColor(myRank.getUser().getLv())));
            if (FamilyAccountManager.getInstance().getFamilyExps() != null
                    && FamilyAccountManager.getInstance().getFamilyUserExps().containsKey(myRank.getUser().getLv())) {
                tv_anchor_family_ranking.setText(FamilyAccountManager.getInstance().getFamilyUserExps().get(myRank.getUser().getLv()).getTitle());
            }

            TextView tv_value_ranking = ViewUtil.findView(this, R.id.tv_value_ranking);
            tv_value_ranking.setText(myRank.getValue() + this.getString(R.string.meili));

            TextView tv_ranking_rank = ViewUtil.findView(this, R.id.tv_ranking_rank);
            if (myRank.getRank() == -1) {
                tv_ranking_rank.setText(R.string.str_family_rank_no_in);
            } else {
                tv_ranking_rank.setText(String.format(this.getString(R.string.ranking_rank), myRank.getRank() + 1));
            }
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        ErrorResult.toastError(this, code);
    }
}
